package com.ellecity06.cwhiskymall.view.dialog

import android.view.LayoutInflater
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.ellecity06.common.base.BaseDialog
import com.ellecity06.common.utils.FileUtil
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.databinding.DialogDownLoadImageBinding
import com.ellecity06.cwhiskymall.helper.DownloadManager
import com.ellecity06.cwhiskymall.utils.FileUtils
import com.ellecity06.cwhiskymall.utils.SaveUtils

/**
 * @author ellecity06
 * @time 2024/11/4 18:23
 * @des
 */

class DownLoadImageDialog(val activity: FragmentActivity, private val images: List<String>) :
    BaseDialog<DialogDownLoadImageBinding>(activity) {
    private val states: MutableList<DownloadState> by lazy { mutableListOf() }
    override fun inflaterViewBinding(): DialogDownLoadImageBinding {
        return DialogDownLoadImageBinding.inflate(LayoutInflater.from(context))
    }

    override val animation: Int
        get() = R.style.animScaleCenter
    override val widthP: Float
        get() = 0.5F

    override fun initialize() {
        setCount()
        activity.lifecycleScope.launchWhenCreated {
            DownloadManager.download(images).collect {
                if ((it is DownloadState.Success)) {
                    states.add(it)
                    setCount()
                    SaveUtils.saveImgFileToAlbum(activity,it.file.absolutePath)
//                    FileUtil.saveImageFileToExternal(
//                        activity,
//                        imageName = it.file.name,
//                        imageFile = it.file
//                    )
                }
                if (states.size == images.size) {
//                    val map =
//                        states.map { if (it is DownloadState.Success) it.file.absolutePath else "" }
//                    FileUtils.notifyAlumb(activity, map.toTypedArray())
                    ToastUtils.show("保存成功")
                    dismiss()
                }
            }
        }

    }

    private fun setCount() {
        binding.tvNum.text = "${states.size}/${images.size}"
    }
}